package uz.rt.dicom.data.element;

import uz.rt.dicom.ValueRepresentation;
import uz.rt.dicom.data.ByteElement;
import uz.rt.dicom.data.ComparableList;
import uz.rt.dicom.io.DicomIOException;
import uz.rt.dicom.io.DicomInputStream;
import uz.rt.dicom.tag.DicomTag;

import java.io.IOException;

public class UnsignedShort extends ByteElement<ComparableList<Integer>> implements Comparable<UnsignedShort>
{
// --------------------------- CONSTRUCTORS ---------------------------

    public UnsignedShort(DicomTag tag)
    {
        super(tag);
        setMaxLength(2);
    }

// --------------------- GETTER / SETTER METHODS ---------------------

    public ComparableList<Integer> getValue()
    {
        return value;
    }

// ------------------------ INTERFACE METHODS ------------------------


// --------------------- Interface Comparable ---------------------

    public int compareTo(UnsignedShort o)
    {
        if (!tag.equals(o.getTag())) return tag.compareTo(o.getTag());
        if (!vm.equals(o.getVm())) return vm.compareTo(o.getVm());
        return value.compareTo(o.getValue());
    }

// --------------------- Interface IDataElement ---------------------

    @Override
    public int getLength()
    {
        return value.size();
    }

    @Override
    public byte[] getVR()
    {
        return ValueRepresentation.US;
    }

    @Override
    public ValueRepresentation getValueRepresentation()
    {
        return ValueRepresentation.UnsignedShort;
    }

    public void read(DicomInputStream dicomInputStream, int length) throws IOException
    {
        int n = length % maxLength;
        if (n != 0)
        {
            value = null;
            throw new DicomIOException(
                    "The modulus of the length and maximum length should be zero.");
        }
        n = length / maxLength;
        if (n < vm.getMin() || n > vm.getMax())
        {
            value = null;
            throw new DicomIOException(
                    "Value multiplicity violation: length = " + n +
                            ", limits are [" + vm.toString() + "]");
        }
        value = null;
        value = new ComparableList<Integer>();
        for (int i = 0; i < n; i++)
            value.add(dicomInputStream.readUnsigned16());
    }
}
